﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using GameStudio.Common;
using GameStudio.IDE.Common.Events;
using Microsoft.Practices.ServiceLocation;
using Utils.EventAggregator;
using GameStudio.IDE.Common;
using GameStudio.IDE.Common.Bootstrappers;

namespace GameStudio.IDE.Controls
{
    [TemplatePart(Name = "lstbxItems", Type = typeof(ListBox))]
    [TemplatePart(Name = "btnOk", Type = typeof(ButtonBase))]
    [TemplatePart(Name = "btnCancel", Type = typeof(ButtonBase))]
    [TemplatePart(Name = "txtName", Type = typeof(TextBox))]


    public class AddNewItemControl:Control
    {
        ListBox lstbxItems;
        ButtonBase btnOk;
        ButtonBase btnCancel;
        TextBox txtName;
        Item item = new Item();

        public override void OnApplyTemplate()
        {
            txtName = (TextBox)GetTemplateChild("txtName");
            lstbxItems = (ListBox)GetTemplateChild("lstbxItems");

            btnOk = (ButtonBase)GetTemplateChild("btnOk");
            btnOk.Click += new RoutedEventHandler(btnOk_Click);

            btnCancel = (ButtonBase)GetTemplateChild("btnCancel");
            btnCancel.Click += new RoutedEventHandler(btnCancel_Click);

            lstbxItems.SelectedItem = lstbxItems.Items[0];
            base.OnApplyTemplate();

        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Window.GetWindow(btnCancel).Close();
        }

        void btnOk_Click(object sender, RoutedEventArgs e)
        {

            if (TabContainer.TabItemsDictionary.ContainsKey(txtName.Text))
            {
                System.Windows.Forms.MessageBox.Show("The name \"" + txtName.Text + "\" already exists! Please choose another name.");
            }
            else if (txtName.Text == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("Please write the name of the item!");
            }
            else
            {
                item.Name = txtName.Text;

                ListBoxItem lbi = (ListBoxItem)lstbxItems.SelectedItem;
                string type = lbi.Content.ToString();

                item.Type = type;

                Session.AddItem(item);

                // fire newItem and openItem
                NewItemTask newItemTask = new NewItemTask();
                newItemTask.Run();

                OpenItemTask openItemTask = new OpenItemTask();
                openItemTask.Run();

                var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
                eventAggregator.GetEvent<AddNewItemEvent>().Publish(item);

                Window.GetWindow(btnOk).Close();
            }
        }
    }
}
